﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ScFramework.Core;
using Ecset = Unity.Entities.Entity;
using Ecsmgr = Unity.Entities.EntityManager;

/// <summary>
/// 注意centercoordInt的原点不是(0,0,0)
/// </summary>
public class Chunk
{
    public Vector2Int centerCoordInt;
    public Vector2 centerCoord;
    private const float _CHUNKSIZE = TerrianManager.CHUNKSIZE;
    private const float _HALFCHUNKSIZE = 0.5f * _CHUNKSIZE;
    public Bounds chunkBound;
    public TerrianQuadTree quadTreeInternal;
    public bool isInstant;

    public static readonly Vector2 CHUNKBASEPOINT = new Vector3(-0.5f * _CHUNKSIZE, -0.5f * _CHUNKSIZE, 0);

    public Chunk(Vector2 centerOri)
    {
        Vector3 center = centerOri - CHUNKBASEPOINT;
        if(((center.x % _HALFCHUNKSIZE) != 0) || ((center.y % _HALFCHUNKSIZE) != 0))
        {
            Debug.LogError("Chunk不对齐，生成不合法1");
            return;
        }
        int tmpX = (int)(center.x / _HALFCHUNKSIZE);
        int tmpY = (int)(center.y / _HALFCHUNKSIZE);
        if ((tmpX % 2 == 0) || (tmpY % 2 == 0))
        {
            Debug.LogError("Chunk不对齐，生成不合法2");
            return;
        }
        this.centerCoordInt.x = tmpX > 0 ? (tmpX + 1) / 2 : (tmpX - 1) / 2;
        this.centerCoordInt.y = tmpY > 0 ? (tmpY + 1) / 2 : (tmpY - 1) / 2;
        this.centerCoord = centerOri;
        chunkBound = new Bounds(centerOri, new Vector3(_CHUNKSIZE, _CHUNKSIZE, _CHUNKSIZE));
        quadTreeInternal = new TerrianQuadTree(new Bounds(centerOri, new Vector3(_CHUNKSIZE, _CHUNKSIZE, _CHUNKSIZE)));
        isInstant = true;
        TerrianManager.chunkList.Add(this);
    }
    public Chunk(Vector2Int centerOriInt)
    {
        Vector2 centerOri = new Vector2();
        centerOri.x = centerOriInt.x * _CHUNKSIZE;
        centerOri.x = centerOri.x > 0 ? centerOri.x - _HALFCHUNKSIZE : centerOri.x + _HALFCHUNKSIZE;
        centerOri.y = centerOriInt.y * _CHUNKSIZE;
        centerOri.y = centerOri.y > 0 ? centerOri.y - _HALFCHUNKSIZE : centerOri.y + _HALFCHUNKSIZE;
        centerOri += CHUNKBASEPOINT;

        //Vector2 center = centerOri + CHUNKBASEPOINT;
        this.centerCoordInt = centerOriInt;
        this.centerCoord = centerOri;
        chunkBound = new Bounds(centerOri, new Vector3(_CHUNKSIZE, _CHUNKSIZE, _CHUNKSIZE));
        quadTreeInternal = new TerrianQuadTree(new Bounds(centerOri, new Vector3(_CHUNKSIZE, _CHUNKSIZE, _CHUNKSIZE)));
        isInstant = true;
        TerrianManager.chunkList.Add(this);
    }
    
    public static Chunk GetOrCreateChunk(Vector2Int key)
    {
        Chunk ans;
        ans = TerrianManager.chunkList.Find(c => c.centerCoordInt == key);
        if (ans != null)
        {
            return ans;
        }
        else
        {
            ans = new Chunk(key);
            return ans;
        }
    }

    public List<TerrianQuadTree.QuadNode> GetChunkCollider()
    {
        var boundList = this.quadTreeInternal.rootNode.GetFullNodes();
        //foreach(var b in boundList)
        //{
        //    if(true)
        //    {
        //        float tmpXL = (b.center - b.size / 2).x;
        //        float tmpYD = (b.center - b.size / 2).y;
        //        float tmpXR = (b.center + b.size / 2).x;
        //        float tmpYU = (b.center + b.size / 2).y;

        //        Debug.DrawLine(new Vector3(tmpXL, tmpYU, 0), new Vector3(tmpXL, tmpYD), Color.white, 0.1f);
        //        Debug.DrawLine(new Vector3(tmpXL, tmpYD, 0), new Vector3(tmpXR, tmpYD), Color.white, 0.1f);
        //        Debug.DrawLine(new Vector3(tmpXR, tmpYD, 0), new Vector3(tmpXR, tmpYU), Color.white, 0.1f);
        //        Debug.DrawLine(new Vector3(tmpXR, tmpYU, 0), new Vector3(tmpXL, tmpYU), Color.white, 0.1f);
        //    }
        //}
        return boundList;
    }

    public void ChunkColliderRemake()  
    {
        //var g = ResourceManager.Instance.Load<GameObject>("Terrian/CC");
        //ObjectPool.RecycleAll(g);
        
        var bl = this.GetChunkCollider();

        foreach (var b in bl)
        {
            GameObject colliderCarrier = ResourceManager.Instance.Instantiate("Terrian/CC");
            colliderCarrier.transform.position = b.bound.center;
            colliderCarrier.transform.localScale = b.bound.size;
            colliderCarrier.GetComponent<ColliderCal>().SetNode(b);
            colliderCarrier.GetComponent<ColliderCal>().belongChunk = this;
            //colliderCarrier.hideFlags = HideFlags.HideInHierarchy;
        }
    }

    /// <summary>
    /// 销毁Entity，保留VoxelComponentData和pos
    /// </summary>
    public void DisposeChunk()
    {
        //if (this.isInstant == false)
         //   return;
        //else
        //{
            this.isInstant = false;
            this.quadTreeInternal.rootNode.DisposeEntity(this.quadTreeInternal.rootNode);
        //}
    }

    /// <summary>
    /// 根据VoxelComponentData和pos重新生成Entity并产生新id
    /// </summary>
    public void GenerateChunk()
    {
        //if (this.isInstant == true)
         //   return;
        //else
        //{
            this.isInstant = true;
            this.quadTreeInternal.rootNode.GenerateEntity(this.quadTreeInternal.rootNode);
        //}
    }

}
